/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  MainViewController.h
//  PushInappTestiOS
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "MainViewController.h"
#import "AppManager.h"

@implementation MainViewController

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    // Set the main view to utilize the entire application frame space of the device.
    // Change this to suit your view's UI footprint needs in your application.
    
    UIView* rootView = [[[[UIApplication sharedApplication] keyWindow] rootViewController] view];
    CGRect webViewFrame = [[[rootView subviews] objectAtIndex:0] frame];  // first subview is the UIWebView
    
    if (CGRectEqualToRect(webViewFrame, CGRectZero)) { // UIWebView is sized according to its parent, here it hasn't been sized yet
        self.view.frame = [[UIScreen mainScreen] applicationFrame]; // size UIWebView's parent according to application frame, which will in turn resize the UIWebView
    }
    
    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUserInterface];
    
    [AppManager getInstance].webview = self.webView;
    // Do any additional setup after loading the view from its nib.
}

#pragma mark - User Define Function
- (void) setUserInterface
{
    CGFloat iphone5_YRES = 0;
    if(IS_IPHONE_5)
    {
        iphone5_YRES = 88.0f;
    }
    
    UIImageView *img_BottomBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 420 + iphone5_YRES, 320, 60)];
    [img_BottomBG setImage:[UIImage imageNamed:@"ui_footer-ui_box.png"]];
    
    UIButton *btnNews = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnNews setFrame:CGRectMake(0, 422 + iphone5_YRES, 50, 50)];
    [btnNews setImage:[UIImage imageNamed:@"ui_footer-ui_btn-news_normal.png"] forState:UIControlStateNormal];
    [btnNews setImage:[UIImage imageNamed:@"ui_footer-ui_btn-news_touch.png"] forState:UIControlStateSelected];
    [btnNews addTarget:self action:@selector(buttonEventListener:) forControlEvents:UIControlEventTouchUpInside];
    [btnNews setTag:BUTTON_INDEX_NEWS];
    
    UIButton *btnMission = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnMission setFrame:CGRectMake(53, 422 + iphone5_YRES, 50, 50)];
    [btnMission setImage:[UIImage imageNamed:@"ui_footer-ui_btn-mission_normal.png"] forState:UIControlStateNormal];
    [btnMission setImage:[UIImage imageNamed:@"ui_footer-ui_btn-mission_touch.png"] forState:UIControlStateSelected];
    [btnMission addTarget:self action:@selector(buttonEventListener:) forControlEvents:UIControlEventTouchUpInside];
    [btnMission setTag:BUTTON_INDEX_MISSION];
    
    UIButton *btnWar = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnWar setFrame:CGRectMake(108, 422 + iphone5_YRES, 50, 50)];
    [btnWar setImage:[UIImage imageNamed:@"ui_footer-ui_btn-war_normal.png"] forState:UIControlStateNormal];
    [btnWar setImage:[UIImage imageNamed:@"ui_footer-ui_btn-war_touch.png"] forState:UIControlStateSelected];
    [btnWar addTarget:self action:@selector(buttonEventListener:) forControlEvents:UIControlEventTouchUpInside];
    [btnWar setTag:BUTTON_INDEX_WAR];
    
    UIButton *btnUnit = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnUnit setFrame:CGRectMake(162, 422 + iphone5_YRES, 50, 50)];
    [btnUnit setImage:[UIImage imageNamed:@"ui_footer-ui_btn-unit_normal.png"] forState:UIControlStateNormal];
    [btnUnit setImage:[UIImage imageNamed:@"ui_footer-ui_btn-unit_touch.png"] forState:UIControlStateSelected];
    [btnUnit addTarget:self action:@selector(buttonEventListener:) forControlEvents:UIControlEventTouchUpInside];
    [btnUnit setTag:BUTTON_INDEX_UNIT];
    
    UIButton *btnBuilding = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnBuilding setFrame:CGRectMake(216, 422 + iphone5_YRES, 50, 50)];
    [btnBuilding setImage:[UIImage imageNamed:@"ui_footer-ui_btn-building_normal.png"] forState:UIControlStateNormal];
    [btnBuilding setImage:[UIImage imageNamed:@"ui_footer-ui_btn-building_touch.png"] forState:UIControlStateSelected];
    [btnBuilding addTarget:self action:@selector(buttonEventListener:) forControlEvents:UIControlEventTouchUpInside];
    [btnBuilding setTag:BUTTON_INDEX_BUILDING];
    
    UIButton *btnGeneral = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnGeneral setFrame:CGRectMake(270, 422 + iphone5_YRES, 50, 50)];
    [btnGeneral setImage:[UIImage imageNamed:@"ui_footer-ui_btn-general_normal.png"] forState:UIControlStateNormal];
    [btnGeneral setImage:[UIImage imageNamed:@"ui_footer-ui_btn-general_touch.png"] forState:UIControlStateSelected];
    [btnGeneral addTarget:self action:@selector(buttonEventListener:) forControlEvents:UIControlEventTouchUpInside];
    [btnGeneral setTag:BUTTON_INDEX_GENERAL];
    
    [self.webView setFrame:CGRectMake(0, 0, 320, 420 + iphone5_YRES)];
    
    [self.view addSubview:img_BottomBG];
    [self.view addSubview:btnNews];
    [self.view addSubview:btnMission];
    [self.view addSubview:btnWar];
    [self.view addSubview:btnUnit];
    [self.view addSubview:btnBuilding];
    [self.view addSubview:btnGeneral];
    [img_BottomBG release];
}

/*
 * 버튼이 눌리면 버튼의 Index를 이용하여 Javascript로 이벤트를 전달합니다.
 */
- (void) buttonEventListener:(id)sender
{
    [self sendButtonEventToHTML:[sender tag]];
}

/*
 * Javascript로 이벤트를 전달합니다.
 * index : 버튼 Tag Index
 * event : COMMON_Event
 */
- (void) sendButtonEventToHTML:(NSInteger)index
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:@"menubutton" forKey:@"event"];
    [dict setObject:[NSString stringWithFormat:@"%d", index] forKey:@"index"];
    
    [[AppManager getInstance] sendJavascript:@"COMMON_Event" data:dict];
    
    [dict release];
}

/*
 * Index값에 따라 메뉴 버튼의 상태를 변경합니다.
 * BridgePlugin의 changemenu 함수에서 호출됩니다.
 */
- (void) controlButtonImage:(NSInteger)index
{
    @try {
        UIButton *selectedButton = (UIButton*)[self.view viewWithTag:index];
        
        for(int i = BUTTON_INDEX_NEWS; i <= BUTTON_INDEX_GENERAL; i ++)
        {
            [(UIButton*)[self.view viewWithTag:i] setSelected:NO];
        }
        
        [selectedButton setSelected:YES];
    }
    @catch (NSException *exception) {
        [[AppManager getInstance] showAlertDialog:@"MainView ButtonControl" with:[exception reason]];
    }
    @finally {

    }
}

/*
 * Push 메시지가 도착하면 Javascript로 웹뷰에 Push 메시지를 알려줍니다.
 */
- (void) sendPushMessage:(NSDictionary*)userInfo
{
    NSLog(@"%s", __FUNCTION__);
    NSInteger notiValue = [[NSString stringWithString:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]] integerValue];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:@"pushmessage" forKey:@"event"];
    [dict setObject:[NSString stringWithFormat:@"%d", notiValue] forKey:@"index"];
    
    [[AppManager getInstance] sendJavascript:@"COMMON_Event" data:dict];
    
    [dict release];
}

/* Comment out the block below to over-ride */

/*
 - (CDVCordovaView*) newCordovaViewWithFrame:(CGRect)bounds
 {
 return[super newCordovaViewWithFrame:bounds];
 }
 */

/* Comment out the block below to over-ride */

/*
 #pragma CDVCommandDelegate implementation
 
 - (id) getCommandInstance:(NSString*)className
 {
 return [super getCommandInstance:className];
 }
 
 - (BOOL) execute:(CDVInvokedUrlCommand*)command
 {
 return [super execute:command];
 }
 
 - (NSString*) pathForResource:(NSString*)resourcepath;
 {
 return [super pathForResource:resourcepath];
 }
 
 - (void) registerPlugin:(CDVPlugin*)plugin withClassName:(NSString*)className
 {
 return [super registerPlugin:plugin withClassName:className];
 }
 */

#pragma mark - UIWebDelegate implementation

- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    // only valid if ___PROJECTNAME__-Info.plist specifies a protocol to handle
    if (self.invokeString) {
        // this is passed before the deviceready event is fired, so you can access it in js when you receive deviceready
        NSLog(@"DEPRECATED: window.invokeString - use the window.handleOpenURL(url) function instead, which is always called when the app is launched through a custom scheme url.");
        NSString* jsString = [NSString stringWithFormat:@"var invokeString = \"%@\";", self.invokeString];
        [theWebView stringByEvaluatingJavaScriptFromString:jsString];
    }
    
    // Black base color for background matches the native apps
    theWebView.backgroundColor = [UIColor blackColor];
    
    return [super webViewDidFinishLoad:theWebView];
}

/* Comment out the block below to over-ride */

/*
 
 - (void) webViewDidStartLoad:(UIWebView*)theWebView
 {
 return [super webViewDidStartLoad:theWebView];
 }
 
 - (void) webView:(UIWebView*)theWebView didFailLoadWithError:(NSError*)error
 {
 return [super webView:theWebView didFailLoadWithError:error];
 }
 
 - (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
 {
 return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
 }
 */
@end
